#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
class Solution
{
public:
struct Compare
{
    bool operator()(const pair<string,int>& x,const pair<string,int>& y)const
    {
        return x.second > y.second;
    }
};
    vector<string> topKFrequent(vector<string> &words, int k)
    {
        map<string, int> countmap;
        for(auto& e : words)
        {
            countmap[e]++;
        }
        vector<pair<string, int>> vp(countmap.begin(), countmap.end());
        stable_sort(vp.begin(), vp.end(),Compare());
        vector<string> v;
        for (int i = 0; i < k;i++)
        {
            v.push_back(vp[i].first);
        }
            return v;
    }
};